<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="MPRIfSpan">
        <div style="background-color: #F2F6FC;padding: 15px">
          <el-button @click="addMedicinePrescriptionRecord" class="el-icon-circle-plus-outline"
                     style="color: #409EFF;padding-right: 15px" type='text'>新增处方
          </el-button>
          <el-button @click="delMedicinePrescriptionRecord" class="el-icon-remove-outline"
                     style="color: #409EFF;padding-right: 15px"
                     :disabled="single"
                     type='text'>删除处方
          </el-button>
          <el-button @click="prescribe" class="el-icon-success" style="color: #409EFF;padding-right: 15px"
                     :disabled="single"
                     type='text'>开立处方
          </el-button>
          <el-button @click="voidPrescription" class="el-icon-error" style="color: #409EFF;padding-right: 15px"
                     :disabled="single"
                     type='text'>作废处方
          </el-button>
          <el-button @click="$alert('暂存')" class="el-icon-upload2" style="color: #409EFF;padding-right: 15px"
                     type='text'>暂存
          </el-button>
          <el-button @click="$alert('取出暂存')" class="el-icon-download" style="color: #409EFF;padding-right: 15px"
                     type='text'>取出暂存
          </el-button>
          <el-button @click="getList" class="el-icon-refresh" style="color: #409EFF;padding-right: 15px" type='text'>
            刷新
          </el-button>
          <el-button @click="showOrHidden" style="margin-left: 30px"><span
            :class=" elIfShow ? 'el-icon-caret-right' : 'el-icon-caret-left' "></span></el-button>
        </div>
        <el-table :data="medicine_prescription_recordList" @selection-change="handleSelectionChange"
                  v-loading="loading">
          <el-table-column :selectable="selectable" type="selection" width="55"></el-table-column>
          <el-table-column align="center" label="处方名" prop="name"/>
          <el-table-column align="center" label="总金额" prop="amount"/>
          <el-table-column align="center" label="成药处方状态">
            <template slot-scope="scope">
              <el-tag :type='onColourLine[scope.row.status]'>{{onLine[scope.row.status]}}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="MMIfSpan" v-show="elIfShow">
        <el-card class="box-card">
          <div class="clearfix" slot="header">
            <span>成药模版</span>
          </div>
          <el-table :data="medicine_modelList" @cell-click="getMedicineModel" @cell-dblclick="addToMPRList">
            <el-table-column align="center" label="模版ID" prop="id" v-if="false"/>
            <el-table-column align="center" label="模版名" prop="name"/>
            <el-table-column align="center" label="目的" prop="aim"/>
          </el-table>
        </el-card>
        <el-card class="box-card">
          <div class="clearfix" slot="header">
            <span>模版详情</span>
          </div>
          <h4>模板名称:{{medicine_model.name}}</h4>
          <h4>模板编码:{{medicine_model.code}}</h4>
          <h4>模版目的:{{medicine_model.aim}}</h4>
          <h4>模板医嘱:{{medicine_model.medicalAdvice}}</h4>
          <h4 v-cloak>总金额:{{model_form.amount}}</h4>
        </el-card>
      </el-col>
    </el-row>

    <!-- 对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="1200px">
      <el-form :inline="true" :model="form" :rules="rules" ref="form">
        <el-row>
          <el-col :span="8">

            <div style="background-color: #F2F6FC;padding: 10px;color: #409EFF">常用药品</div>
            <el-table :data="usedMedicineList" @row-click="addDrug" style="max-height: 250px;overflow: auto;">
              <el-table-column align="center" label="ID" prop="id" v-if="false"/>
              <el-table-column align="center" label="药品名" prop="name"/>
              <el-table-column align="center" label="价格(元)" prop="price"/>
            </el-table>

            <div style="background-color: #F2F6FC;padding: 10px;color: #409EFF">药品目录
              <el-input
                clearable
                placeholder="药品名称"
                size="mini"
                style="width: 250px;margin-right: 10px"
                v-model="drug.name"
              />
              <span @click="getDrugList" class="el-icon-search"
                    style="color: white;background-color: #409EFF;padding: 10px;border-radius: 30px"></span>
            </div>

            <el-table :data="drugList" @row-click="addDrug" style="max-height: 250px;overflow: auto;">
              <el-table-column align="center" label="ID" prop="id" v-if="false"/>
              <el-table-column align="center" label="药品名" prop="name"/>
              <el-table-column align="center" label="价格(元)" prop="price"/>
            </el-table>

            <pagination
              layout="prev, pager, next"
              :limit.sync="drug.pageSize"
              :page-sizes=null
              :page.sync="drug.pageNum"
              :total="total"
              @pagination="getDrugList"
              small
              v-show="total>0"
            />

          </el-col>
          <el-col :span="16">
            <div style="margin-left: 10px">
              <el-tag disabled plain type="primary">项目金额总计:</el-tag>
              <el-tag disabled plain type="warning">{{this.form.amount}}元</el-tag>
              <el-form-item class="top-right-btn" prop="name">
                <el-input
                  clearable
                  placeholder="处方名称"
                  size="medium"
                  v-model="form.name"
                />
              </el-form-item>
              <el-button @click="submitForm" class="top-right-btn" type="primary">增加处方</el-button>
              <el-table :data="prescriptionDrugList" style="max-height: 450px;overflow: auto;" width="600px">
                <el-table-column align="center" prop="del">
                  <template slot-scope="scope">
                    <a @click="del(scope.$index,scope.row)">删除</a>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="药品id" prop="drugId" v-if="false"/>
                <el-table-column align="center" label="药品名" prop="name"/>
                <el-table-column align="center" label="规格" prop="format" v-if="false"/>
                <el-table-column align="center" label="单价" prop="price"/>
                <el-table-column align="center" label="数量" width="150px">
                  <template slot-scope="scope">
                    <el-input-number :max="10" :min="1" @change="amountSettlement" size="mini"
                                     v-model="prescriptionDrugList[scope.$index].num"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="使用方法" prop="medicineUsage">
                  <template slot-scope="scope">
                    <el-select id="medicineUsage" placeholder="方法" size="small"
                               v-model="prescriptionDrugList[scope.$index].medicineUsage">
                      <el-option
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                        v-for="dict in methodOptions"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="使用频次" prop="frequency">
                  <template slot-scope="scope">
                    <el-select id="frequency" placeholder="频次" size="small"
                               v-model="prescriptionDrugList[scope.$index].frequency">
                      <el-option
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                        v-for="dict in frequencyOptions"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="天数" prop="days">
                  <template slot-scope="scope">
                    <el-input v-model="prescriptionDrugList[scope.$index].days"></el-input>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="用量" prop="usageNum">
                  <template slot-scope="scope">
                    <el-input v-model="prescriptionDrugList[scope.$index].usageNum"></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addMedicine_prescription_record,
    delMedicine_prescription_record_remove,
    listMedicine_prescription_record,
    prescribe_over_counter_medicines,
    void_prescription_over_counter_medicines
  } from "@/api/dms/medicine_prescription_record";
  import {getDrug_model, listDrug_model} from "@/api/dms/drug_model";
  import {getDrug, listDrug} from "@/api/dms/drug";
  import {listUsed} from "@/api/dms/used";
  import {getMedicine_model_item_by_modelId} from "@/api/dms/medicine_model_item";

  export default {
    name: "Medicine_prescription_record",
    // 接收父组件传参
    props: ["registrationId"],
    data() {
      return {
        title: null,
        /**赋予挂号id初始值 用于测试*/
        //registrationId:2,
        // 遮罩层
        loading: true,
        // 非单个禁用
        single: true,
        // 成药处方表格数据
        medicine_prescription_recordList: [],
        // 是否显示弹出层
        open: false,
        // 成药模板显示与隐藏
        elIfShow: false,
        // 成药列表跨列数
        MPRIfSpan: 24,
        // 成药模板列表跨列数
        MMIfSpan: 0,
        // 成药处方状态字典
        statusOptions: [],
        // 状态的对应的值 DELETED(0, "作废/删除"),
        onLine: {"-1": "未开立", "0": "作废", "1": "新建/未缴费", "2": "已缴费", "3": "已发药", "4": "已退药", "5": "已退费", "6": "已过期"},
        // 状态的对应的颜色
        onColourLine: {
          "-1": "success",
          "0": "warning",
          "1": "info",
          "2": "success",
          "3": "warning",
          "4": "success",
          "5": "warning",
          "6": "info"
        },
        //模板范围字典表
        scopeOptions: [],
        //药品使用方法字典
        methodOptions: [],
        //药品使用频次字典
        frequencyOptions: [],
        //模版集合
        medicine_modelList: [],
        //模板详情对象
        medicine_model: {
          name: null,
          code: null,
          aim: null,
          therapy: null,
          medicalAdvice: null,
          therapyDetails: null
        },
        //成药处方表单对象
        form: {
          amount: 0,
          status: -1,
          name: null,
          registrationId: null,
          medicineItemRecords: []
        },
        //从模板添加成药处方对象
        model_form: {
          amount: 0,
          status: -1,
          name: null,
          registrationId: null,
          medicineItemRecords: []
        },
        //药品参数
        drug: {
          pageNum: 1,
          pageSize: 10,
          typeId: -103,
          name: null
        },
        //药品集合
        drugList: [],
        //常用成药集合
        usedMedicineList: [],
        //处方药品集合
        prescriptionDrugList: [],
        // 总条数
        total: 0,
        //选中数组，名称集合
        names: [],
        //表单验证
        rules: {
          name: [
            {required: true, message: "处方名不能为空", trigger: "blur"}
          ]
        }
      };
    },
    created() {
      this.getList();
      this.getMedicineModelList();
      this.getDicts("medicine_prescription_status").then(response => {
        this.statusOptions = response.data;
      });
      this.getDicts("drug_use_method").then(response => {
        this.methodOptions = response.data;
      });
      this.getDicts("drug_use_frequency").then(response => {
        this.frequencyOptions = response.data;
      });
    },
    methods: {
      /** 查询成药处方列表 */
      getList() {
        this.loading = true;
        listMedicine_prescription_record({"registrationId": this.registrationId}).then(response => {
          this.medicine_prescription_recordList = response.rows;
          this.loading = false;
        });
      },
      //控制模板显示与隐藏
      showOrHidden() {
        this.elIfShow = !this.elIfShow;
        if (this.elIfShow) {
          this.MPRIfSpan = 16;
          this.MMIfSpan = 8;
        } else {
          this.MPRIfSpan = 24;
          this.MMIfSpan = 0;
        }
      },
      //查询模版集合
      getMedicineModelList() {
        listDrug_model({"type": 1}).then(response => {
          this.medicine_modelList = response.rows;
        });
      },
      //查询成药模板详情
      getMedicineModel(row, event, column) {
        this.setModel(row.id);
        getDrug_model(row.id).then(response => {
          this.medicine_model = response.data;
        });
      },
      //新增成药处方弹框
      addMedicinePrescriptionRecord() {
        this.title = "新增成药处方";
        this.open = true;
        this.getDrugList();
      },
      //获取成药列表
      getDrugList() {
        listDrug(this.drug).then(value => {
          this.drugList = value.rows;
          this.total = value.total;
        });
        listUsed({"projectType": 103}).then(value => {
          this.usedMedicineList = value.rows;
        });
      },
      /**点击添加药品*/
      addDrug(row, event, column) {
        if (this.drugCheck(row.id)) {
          getDrug(row.id).then(value => {
            this.prescriptionDrugList.push({
              drugId: parseInt(value.data.id),
              name: value.data.name,
              format: value.data.format,
              price: value.data.price,
              usageNumUnit: value.data.dosageId,
              num: 1
            });
            this.amountSettlement();
          });
        }
      },
      /**药品查重*/
      drugCheck(id) {
        let list = this.prescriptionDrugList;
        for (let i = 0; i < list.length; i++) {
          if (id === list[i].drugId) {
            list[i].num += 1;//如果药品重复，就在数量上加一
            this.amountSettlement();
            return false;
          }
        }
        return true;
      },
      /**金额结算*/
      amountSettlement() {
        let price = 0;
        this.prescriptionDrugList.forEach(value => {
          price += value.price * value.num;
        });
        this.form.amount = price;
      },
      /**删除*/
      del(index, row) {
        this.prescriptionDrugList.splice(index, 1);
        this.amountSettlement();
      },
      /**赋值给form中的数组*/
      set() {
        this.form.registrationId = this.registrationId;
        this.form.medicineItemRecords = this.prescriptionDrugList;
      },
      /**赋值给model_form*/
      setModel(id) {
        let totalPrice = 0;
        this.model_form.registrationId = this.registrationId;
        this.model_form.name = this.medicine_model.name;
        getMedicine_model_item_by_modelId(id).then(mmi_response => {
          this.model_form.medicineItemRecords = mmi_response.rows;
          this.model_form.medicineItemRecords.forEach(value => {
            totalPrice += value.drugPrice * value.num;
          });
          this.model_form.amount = totalPrice;
        });
      },
      /**新增成药处方*/
      submitForm() {
        this.set();
        this.$refs["form"].validate(valid => {
          if (valid) {
            addMedicine_prescription_record(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        });
      },
      //从模板添加成药处方
      addToMPRList(row, event, column) {
        if (confirm("确定添加成药处方:" + row.name + "的处方吗？")) {
          this.getMedicineModel(row, event, column);
          if (this.modelCheck(row.name)) {
            addMedicine_prescription_record(JSON.stringify(this.model_form)).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.getList();
              }
            });
          } else {
            this.msgInfo("该模板已存在");
          }
        }
      },
      /**模板查重*/
      modelCheck(name) {
        let list = this.medicine_prescription_recordList;
        for (let i = 0; i < list.length; i++) {
          if (name === list[i].name) {
            return false;
          }
        }
        return true;
      },
      /**是否可选*/
      selectable(row, index) {
        return row.status < 0;
      },
      /** 多选框选中数据 */
      handleSelectionChange(selection) {
        this.names = selection.map(item => item.name);
        this.single = !selection.length;
      },
      /**删除处方*/
      delMedicinePrescriptionRecord() {
        if (confirm("确定删除" + this.names + "的处方吗？")) {
          delMedicine_prescription_record_remove(this.registrationId, this.names);
          this.msgSuccess("删除成功");
          this.getList();
        }
      },
      /**开立处方*/
      prescribe() {
        if (confirm("确定开立" + this.names + "的处方吗？")) {
          prescribe_over_counter_medicines(this.registrationId, this.names);
          this.msgSuccess("开立成功");
          this.getList();
        }
      },
      /**作废处方*/
      voidPrescription() {
        if (confirm("确定作废" + this.names + "的处方吗？")) {
          void_prescription_over_counter_medicines(this.registrationId, this.names);
          this.msgSuccess("操作成功");
          this.getList();
        }
      }
    }
  };
</script>
